package cn.fintecher.pangolin.common.utils;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.compress.utils.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
 * @Author: PeiShouWen
 * @Description: 解压缩文件
 * @Date 10:34 2017/3/25
 */
public class UnReduceFile {

    private final static Logger logger = LoggerFactory.getLogger(UnReduceFile.class);

    /**
     * 解压ZIP压缩文件
     *
     * @param input 源文件流
     * @param targetFile  目标文件路径
     * @param charset     源文件编码
     * @return 返回文件目录记录
     */
    public static List<String> unZip(InputStream input, String targetFile, String charset) throws IOException {
        StopWatch stopWatch=new StopWatch();
        stopWatch.start();
        List<String> directoryList = new ArrayList<>();
        try (ZipArchiveInputStream inputStream = new ZipArchiveInputStream(input)) {
            File pathFile = new File(targetFile);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            ZipArchiveEntry entry = null;
            while ((entry = inputStream.getNextZipEntry()) != null) {
                if (entry.isDirectory()) {
                    directoryList.add(entry.getName().trim());
                    File directory = new File(targetFile, entry.getName());
                    directory.mkdirs();
                } else {
                    OutputStream os = null;
                    try {
                        os = new BufferedOutputStream(new FileOutputStream(new File(targetFile, entry.getName())));
                        //输出文件路径信息
                        logger.info("解压文件的当前路径为:{}", targetFile + entry.getName());
                        IOUtils.copy(inputStream, os);
                    } finally {
                        IOUtils.closeQuietly(os);
                    }
                }
            }
            stopWatch.stop();
            logger.info("解压完毕,耗时:{}",stopWatch.getTotalTimeMillis());
        } catch (Exception e) {
            logger.error("[unzip] 解压zip文件出错", e);
        }
        return directoryList;
    }
}
